/*

Input: newdata/estimation_prep_ltw18 [prepared precinct-level panel]
	
Output:
	- Figure C.1, D.11, D.12
	- Table E.5
		
Main Tasks: 
	* Estimate event study using novel DiD estimators (robustness check)
	* Test of inattention  hypothesis: investigate sign and size 
		of t_1 - t_0 (change in turnout between period 1 and period 0 (event))
		
		
*/	
	
* PULL: Precinct-level data
	use "$newdata/estimation_prep_ltw18.dta", clear
	
********************************************************************************
	//	 Prep Estimation //
********************************************************************************

// label outcomes for figure 
lab var turnout_urne 	"{bf:Panel A.} Effect on Polling Place Turnout"
lab var turnout_pos_req "{bf:Panel B.} Effect on Mail-in Turnout"
lab var turnout_tot_req "{bf:Panel C.} Effect on Total Turnout"
	
********************************************************************************
/*** Robustness to Novel DiD Estimates  (Figre C1)
	
	> Baseline Specification: smpl_trim=1,i.e., treat=100% reassignments, trim after "second event", 
	> No other sample Restriction
	
	Following commands required:
		- did_imputation (Borusyak et al. 2021): available on SSC
		- did_multiplegt (de Chaisemartin and D'Haultfoeuille 2020): available on SSC
		- eventstudyinteract (San and Abraham 2020): available on SSC
		- csdid (Callaway and Sant'Anna 2020): available on SSC
*/
********************************************************************************


foreach v of varlist turnout_urne turnout_pos_req turnout_tot_req {	
	
	* BJS (2021) (weights possible)
	did_imputation `v' sb_new wahl_id Ei if smpl_trim==1 [aw=wahlber_gesamt], autosample pretrends(4) horizons(0/2) cluster(sb_new) maxit(3000) controls($ctr)
	estimates store bjs 
	
	* Estimation with did_multiplegt of de Chaisemartin and D'Haultfoeuille (2020) (NO weights allowed)
	did_multiplegt `v' sb_new wahl_id D  if smpl_trim==1, robust_dynamic dynamic(2) placebo(4) firstdiff_placebo breps(100) seed(100) cluster(sb_new)  controls($ctr) covariances

	matrix dcdh_b = e(estimates) // storing the estimates
	matrix dcdh_v = e(variances)

	* TWFE OLS (weights possible)
	cap drop L* F*
	forvalues l = 7(-1)1 {
		gen F`l'event = K==-`l'
	}	
	forvalues l = 0/7 {
		gen L`l'event = K==`l'
	}	
	order F1event, last
	reghdfe `v' F7event-L7event F1event $ctr [aw=wahlber_gesamt] if smpl_trim ==1, absorb(i.wahl_id i.sb_new) cluster(sb_new)
	estimates store ols	
	
	
	* Estimation with eventstudyinteract of Sun and Abraham (2020) (weights allowed)
	cap drop L* F*
	cap drop lastcohort
	sum Ei
	gen lastcohort = Ei==r(max) // dummy for the latest- or never-treated cohort
	forvalues l = 7(-1)1 {
		gen F`l'event = K==-`l'
	}	
	forvalues l = 0/7 {
		gen L`l'event = K==`l'
	}
	order F1event, last
	eventstudyinteract `v' F7event-L7event F1event if smpl_trim==1 [aw=wahlber_gesamt], ///
		vce(cluster sb_new) absorb(i.wahl_id i.sb_new) cohort(Ei) control_cohort(lastcohort) covariates($ctr)
	
	matrix sa_b = e(b_iw) // storing the estimates
	matrix sa_v = e(V_iw)	

	* Estimation with csdid of Callaway and Sant'Anna (2020) (weights allowed)	
	cap drop gvar
	gen gvar = cond(Ei==., 0, Ei) 					
	csdid `v' $ctr  if smpl_trim==1 [w=wahlber_gesamt] , ivar(sb_new) time(wahl_id) gvar(gvar) notyet agg(event) method(dripw)
	estat event, estore(cs) 									
								
*** Combine all plots using the stored estimates
	event_plot  bjs dcdh_b#dcdh_v cs ols sa_b#sa_v , ///
	stub_lag(tau# Effect_# Tp# L#event L#event ) stub_lead(pre# Placebo_# Tm# F#event F#event ) plottype(scatter) ciplottype(rcap) ///
	together perturb(-0.325(0.13)0.325) trimlead(4) trimlag(2) noautolegend ///
	graph_opt(title("`:var lab `v''", nobox span bexpand justification(left) size(medium)) ///
		xtitle("Election since reassignment", size(medsmall)) ///
		ytitle("Voter turnout in %""(estimates)") xlabel(-4(1)2) ///
		legend(pos(6) order(1 "Borusyak et al. (2022)" 3 "de Chaisemartin & D'Haultfoeuille (2020)" 5 "Callaway & Sant'Anna (2021)" 7 "TWFE OLS" 9 "Sun & Abraham (2021)") col(2) region(style(none)) size(vsmall)) ///
		xline(-0.5, lcolor(black) lpattern(solid)) yline(0, lcolor(gray) lpat(solid))  ylabel(, angle(horizontal)) ///
		name(`v',replace) ) ///
	lag_opt1(msymbol(+) 	msize(3pt) color(black)) 		lag_ci_opt1(color(black)) ///
	lag_opt2(msymbol(O) 	msize(3pt) color(midblue)) 		lag_ci_opt2(color(midblue)) ///
	lag_opt3(msymbol(Dh) 	msize(3pt) color(dkorange)) 	lag_ci_opt3(color(dkorange)) ///
	lag_opt4(msymbol(Th) 	msize(3pt) color(teal)) 		lag_ci_opt4(color(teal)) ///
	lag_opt5(msymbol(Sh) 	msize(3pt) color(cranberry)) 	lag_ci_opt5(color(cranberry)) 
}

	* PLOT: FIGURE C1. Sensitivity to Different Estimators
	grc1leg  turnout_urne turnout_pos_req turnout_tot_req , xcommon  col(2) iscale(.65) imargins(small) pos(12)
	gr_edit .style.editstyle declared_ysize(4) editcopy
	gr_edit .legend.DragBy -60 40
	gr_edit .legend.Edit , style(cols(1)) style(rows(0)) keepstyles
	gr_edit .legend.title.text.Arrpush "Estimator:"
	gr_edit .legend.title.style.editstyle size(small) editcopy
	gr_edit .legend.title.DragBy 0 -15 
	graph export "$figures/Figure_C1_ES_novel_ctr_wgt.pdf", replace	


 

********************************************************************************
 // Test of Mechanism: ES  on sample with distance INCREASES + Never treated (Figure D11) //
********************************************************************************


// create frame to post test results to
cap frame drop   testsUp
	frame create testsUp str10 estimator str20 turnout str20 delta double(p t)
	
foreach v of varlist turnout_urne turnout_pos_req turnout_tot_req {	
	
		
	* BJS (2021) (weights possible)
	did_imputation `v' sb_new wahl_id Ei if smpl_trim_dist==1 [aw=wahlber_gesamt], autosample pretrends(4) horizons(0/2) cluster(sb_new) maxit(3000) controls($ctr)
	estimates store bjs 
	
	// test: t_1 - t_0
	lincom tau1-tau0 	
	local diff = "`:di %8.3f `r(estimate)''"
	stars `r(p)',	stat(p)
	local delta "`diff'`r(stars)'"
	
	frame post testsUp ("BJS (2021)") ("`v'") ("`delta'") (`r(p)') (.)

	* Estimation with did_multiplegt of de Chaisemartin and D'Haultfoeuille (2020) (NO weights allowed)
	did_multiplegt `v' sb_new wahl_id D  if smpl_trim_dist==1, ///
		robust_dynamic dynamic(2) placebo(4) firstdiff_placebo breps(100) seed(100) cluster(sb_new)  covariances controls($ctr) weight(wahlber_gesamt)
	matrix dcdh_b = e(estimates) // storing the estimates
	matrix dcdh_v = e(variances)
	
	// test: t_1 - t_0	
	local  diff = e(effect_1)-e(effect_0) 
	local diff = "`:di %8.3f `diff''"	
	local  se = sqrt(e(se_effect_1)^2+e(se_effect_0)^2-2*e(cov_effects_0_1)) // SE of t_1 - t_0
	local  tstat = `diff'/`se'
	stars `tstat',	stat(t)
	local delta "`diff'`r(stars)'"	
	frame post testsUp ("dCDH (2020)") ("`v'") ("`delta'") (.) (`r(t)')
	
	
	* TWFE OLS (weights possible)
	cap drop L* F*
	forvalues l = 7(-1)1 {
		gen F`l'event = K==-`l'
	}	
	forvalues l = 0/7 {
		gen L`l'event = K==`l'
	}	
		reghdfe `v' F7event-F2event L0event-L7event F1event $ctr [aw=wahlber_gesamt] if smpl_trim_dist ==1, absorb(i.wahl_id i.sb_new) cluster(sb_new)
	estimates store ols	
	
	// test: t_1 - t_0
	lincom L1event-L0event
	local diff = "`:di %8.3f `r(estimate)''"
	stars `r(p)',	stat(p)
	local delta "`diff'`r(stars)'"
	frame post testsUp ("TWFE-OLS") ("`v'") ("`delta'") (`r(p)') (.)
		
	
	* Estimation with eventstudyinteract of Sun and Abraham (2020) (weights allowed)
	cap drop L* F*
	cap drop lastcohort
	sum Ei
	gen lastcohort = Ei==r(max) // dummy for the latest- or never-treated cohort
	forvalues l = 7(-1)1 {
		gen F`l'event = K==-`l'
	}	
	forvalues l = 0/7 {
		gen L`l'event = K==`l'
	}
	order F1event, last
	eventstudyinteract `v' F7event-L7event F1event  if smpl_trim_dist==1 [aw=wahlber_gesamt], vce(cluster sb_new) absorb(sb_new wahl_id) cohort(Ei) control_cohort(lastcohort) covariates($ctr)
	
	matrix sa_b = e(b_iw) 
	matrix sa_v = e(V_iw)
	
	// test: t_1 - t_0
	 matrix b = e(b_iw)
     matrix V = e(V_iw)
     ereturn post b V
	lincom L1event-L0event
	local diff = "`:di %8.3f `r(estimate)''"
	stars `r(p)',	stat(p)
	local delta "`diff'`r(stars)'"
	frame post testsUp ("SA (2020)") ("`v'") ("`delta'") (`r(p)') (.)
		
	* Estimation with csdid of Callaway and Sant'Anna (2020) (weights allowed)	
	cap drop gvar
	gen gvar = cond(Ei==., 0, Ei) 					
	csdid `v'  if smpl_trim_dist==1 [w=wahlber_gesamt] , ivar(sb_new) time(wahl_id) gvar(gvar) notyet agg(event) method(dripw)
	estat event, estore(cs) 									
				
	// test: t_1 - t_0
	local diff 	= e(b)[1,10]-e(b)[1,9]
	local diff = "`:di %8.3f `diff''"
	local se 	= sqrt(e(V)[10,10]+e(V)[9,9]-2*e(V)[10,9]) // SE of t_1-t_0
	local tstat = `diff'/`se'
	stars `tstat',	stat(t)
	local delta "`diff'`r(stars)'"
	frame post testsUp ("CS (2021)") ("`v'") ("`delta'") (.) (`r(t)') 
	
		
*** Combine all plots using the stored estimates

	event_plot  bjs dcdh_b#dcdh_v cs ols sa_b#sa_v , ///
	stub_lag(tau# Effect_# Tp# L#event L#event ) stub_lead(pre# Placebo_# Tm# F#event F#event ) plottype(scatter) ciplottype(rcap) ///
	together perturb(-0.325(0.13)0.325) trimlead(4) trimlag(2) noautolegend ///
	graph_opt(title("`:var lab `v''", nobox span bexpand justification(left) size(medium)) ///
		xtitle("Election since reassignment", size(medsmall)) ///
		ytitle("Voter turnout in %""(estimates)") xlabel(-4(1)2) ///
		legend(pos(6) order(1 "Borusyak et al. (2022)" 3 "de Chaisemartin & D'Haultfoeuille (2020)" 5 "Callaway & Sant'Anna (2021)" 7 "TWFE OLS" 9 "Sun & Abraham (2021)") col(2) region(style(none)) size(vsmall)) ///
		xline(-0.5, lcolor(black) lpattern(solid)) yline(0, lcolor(gray) lpat(solid))  ylabel(, angle(horizontal)) ///
		name(`v',replace) ) ///
	lag_opt1(msymbol(+) 	msize(3pt) color(black)) 		lag_ci_opt1(color(black)) ///
	lag_opt2(msymbol(O) 	msize(3pt) color(midblue)) 		lag_ci_opt2(color(midblue)) ///
	lag_opt3(msymbol(Dh) 	msize(3pt) color(dkorange)) 	lag_ci_opt3(color(dkorange)) ///
	lag_opt4(msymbol(Th) 	msize(3pt) color(teal)) 		lag_ci_opt4(color(teal)) ///
	lag_opt5(msymbol(Sh) 	msize(3pt) color(cranberry)) 	lag_ci_opt5(color(cranberry))
}
	* PLOT: FIGURE D11. Event Study Results Restricted to Units with Increased Distance
	grc1leg  turnout_urne turnout_pos_req turnout_tot_req , xcommon  col(2) iscale(.65) imargins(small) pos(12)
	gr_edit .style.editstyle declared_ysize(4) editcopy
	gr_edit .legend.DragBy -60 40
	gr_edit .legend.Edit , style(cols(1)) style(rows(0)) keepstyles
	gr_edit .legend.title.text.Arrpush "Estimator:"
	gr_edit .legend.title.style.editstyle size(small) editcopy
	gr_edit .legend.title.DragBy 0 -15
	graph export "$figures/Figure_D11_ES_novel_ctr_wgt_dist_increase.pdf", replace	

* Save: first part of Table E5 (appended and exported below)
	frame testsUp: drop p t 
	frame testsUp: reshape wide delta, i(estimator) j(turnout) string
	frame testsUp: rename delta* *
	frame testsUp: list
	// save and append below	
	frame testsUp: save "$tmp/ES_test_tau1_tau2_only_dist_up.dta", replace 			
	
	
********************************************************************************
 // Test of Mechanism: ES conditional on log distance, novel DID (Fiure D12) //
********************************************************************************

// create frame to post test results to
cap frame drop testsAbs
	frame create testsAbs str10 estimator str20 turnout str20 delta double(p t)

foreach v of varlist turnout_urne turnout_pos_req turnout_tot_req {	
	
	* BJS (2021) (weights possible)
	did_imputation `v' sb_new wahl_id Ei if smpl_trim==1 [aw=wahlber_gesamt], autosample pretrends(4) horizons(0/2) cluster(sb_new) maxit(3000) controls($ctr ln_street_dist)
	estimates store bjs 
	
	// test: t_1 - t_0
	lincom tau1-tau0 	
	local diff = "`:di %8.3f `r(estimate)''"
	stars `r(p)',	stat(p)
	local delta "`diff'`r(stars)'"
	frame post testsAbs ("BJS (2021)") ("`v'") ("`delta'") (`r(p)') (.)

	* Estimation with did_multiplegt of de Chaisemartin and D'Haultfoeuille (2020) (NO weights allowed)
	did_multiplegt `v' sb_new wahl_id D  if smpl_trim==1, robust_dynamic dynamic(2) placebo(4) firstdiff_placebo breps(100) seed(100) cluster(sb_new)  controls($ctr ln_street_dist) covariances

	matrix dcdh_b = e(estimates) // storing the estimates
	matrix dcdh_v = e(variances)
	
	// test: t_1 - t_0	
	local  diff = e(effect_1)-e(effect_0) //  t_1 - t_0
	local diff = "`:di %8.3f `diff''"	
	local  se = sqrt(e(se_effect_1)^2+e(se_effect_0)^2-2*e(cov_effects_0_1)) // SE
	local  tstat = `diff'/`se'
	stars `tstat',	stat(t)
	local delta "`diff'`r(stars)'"	
	frame post testsAbs ("dCDH (2020)") ("`v'") ("`delta'") (.) (`r(t)')
	
	* TWFE OLS (weights possible)
	cap drop L* F*
	forvalues l = 7(-1)1 {
		gen F`l'event = K==-`l'
	}	
	forvalues l = 0/7 {
		gen L`l'event = K==`l'
	}	
		reghdfe `v' F7event-F2event L0event-L7event F1event $ctr  ln_street_dist [aw=wahlber_gesamt] if smpl_trim ==1, absorb(i.wahl_id i.sb_new) cluster(sb_new)
	estimates store ols	
	
	// test: t_1 - t_0
	lincom L1event-L0event
	local diff = "`:di %8.3f `r(estimate)''"
	stars `r(p)',	stat(p)
	local delta "`diff'`r(stars)'"
	frame post testsAbs ("TWFE-OLS") ("`v'") ("`delta'") (`r(p)') (.)	
	
	* Estimation with eventstudyinteract of Sun and Abraham (2020) (weights allowed)
	cap drop L* F*
	cap drop lastcohort
	sum Ei
	gen lastcohort = Ei==r(max) // dummy for the latest- or never-treated cohort
	forvalues l = 7(-1)1 {
		gen F`l'event = K==-`l'
	}	
	forvalues l = 0/7 {
		gen L`l'event = K==`l'
	}
	order F1event, last
	eventstudyinteract `v' F7event-L7event F1event  if smpl_trim==1 [aw=wahlber_gesamt], vce(cluster sb_new) absorb(sb_new wahl_id) cohort(Ei) control_cohort(lastcohort) covariates($ctr  ln_street_dist)
	
	matrix sa_b = e(b_iw) // storing the estimates
	matrix sa_v = e(V_iw)
	
	// test: t_1 - t_0
	 matrix b = e(b_iw)
     matrix V = e(V_iw)
     ereturn post b V
	lincom L1event-L0event
	local diff = "`:di %8.3f `r(estimate)''"
	stars `r(p)',	stat(p)
	local delta "`diff'`r(stars)'"
	frame post testsAbs ("SA (2020)") ("`v'") ("`delta'") (`r(p)') (.)
	

	* Estimation with csdid of Callaway and Sant'Anna (2020) (weights allowed ); Version. v1.72
	cap drop gvar
	gen gvar = cond(Ei==., 0, Ei) 					// group variable as required for the csdid command
	csdid `v' $ctr  ln_street_dist  if smpl_trim==1 [w=wahlber_gesamt] , ivar(sb_new) time(wahl_id) gvar(gvar) notyet agg(event) method(dripw)
	estat event, estore(cs) 						// this produces and stores the estimates at the same time			
				
	// test: t_1 - t_0
	local diff 	= e(b)[1,10]-e(b)[1,9] 
	local diff = "`:di %8.3f `diff''"
	local se 	= sqrt(e(V)[10,10]+e(V)[9,9]-2*e(V)[10,9]) 
	local tstat = `diff'/`se'
	stars `tstat',	stat(t)
	local delta "`diff'`r(stars)'"
	frame post testsAbs ("CS (2021)") ("`v'") ("`delta'") (.) (`r(t)')	
				
*** Combine all plots using the stored estimates

	event_plot  bjs dcdh_b#dcdh_v cs ols sa_b#sa_v , ///
	stub_lag(tau# Effect_# Tp# L#event L#event ) stub_lead(pre# Placebo_# Tm# F#event F#event ) plottype(scatter) ciplottype(rcap) ///
	together perturb(-0.325(0.13)0.325) trimlead(4) trimlag(2) noautolegend ///
	graph_opt(title("`:var lab `v''", nobox span bexpand justification(left) size(medium)) ///
		xtitle("Election since reassignment", size(medsmall)) ///
		ytitle("Voter turnout in %""(estimates)") xlabel(-4(1)2) ///
		legend(pos(6) order(1 "Borusyak et al. (2022)" 3 "de Chaisemartin & D'Haultfoeuille (2020)" 5 "Callaway & Sant'Anna (2021)" 7 "TWFE OLS" 9 "Sun & Abraham (2021)") col(2) region(style(none)) size(vsmall)) ///
		xline(-0.5, lcolor(black) lpattern(solid)) yline(0, lcolor(gray) lpat(solid))  ylabel(, angle(horizontal)) ///
		name(`v',replace) ) ///
	lag_opt1(msymbol(+) 	msize(3pt) color(black)) 		lag_ci_opt1(color(black)) ///
	lag_opt2(msymbol(O) 	msize(3pt) color(midblue)) 		lag_ci_opt2(color(midblue)) ///
	lag_opt3(msymbol(Dh) 	msize(3pt) color(dkorange)) 	lag_ci_opt3(color(dkorange)) ///
	lag_opt4(msymbol(Th) 	msize(3pt) color(teal)) 		lag_ci_opt4(color(teal)) ///
	lag_opt5(msymbol(Sh) 	msize(3pt) color(cranberry)) 	lag_ci_opt5(color(cranberry))
}

	* PLOT: FIGURE D12. Event Study Results Absorbing the Distance Effect
	grc1leg  turnout_urne turnout_pos_req turnout_tot_req , xcommon  col(2) iscale(.65) imargins(small) pos(12)
	gr_edit .style.editstyle declared_ysize(4) editcopy
	gr_edit .legend.DragBy -60 40
	gr_edit .legend.Edit , style(cols(1)) style(rows(0)) keepstyles
	gr_edit .legend.title.text.Arrpush "Estimator:"
	gr_edit .legend.title.style.editstyle size(small) editcopy
	gr_edit .legend.title.DragBy 0 -15
	graph export "$figures/Figure_D12_ES_novel_ctr_wgt_ln_dist.pdf", replace	

			
* Table E5. Differences between t_1 and t_0, novel DiD estimators
	/* append and export tex table */
	frame testsAbs{
		drop p t 
		reshape wide delta, i(estimator) j(turnout) string
		rename delta* *					
		list
		set obs 6
		sort estimator
		replace estimator = "\multicolumn{4}{l}{\textit{Panel B: Differences based on event study estimates conditional on log distance}}" if estimator==""
		gen eq=_n*100
		set obs 7
		replace estimator = "\multicolumn{4}{l}{\textit{Panel A: Differences based on event study estimates restricted to precincts with increased distance}} " if estimator==""
		append using "$tmp/ES_test_tau1_tau2_only_dist_up"
		replace eq=_n if eq==.
		sort eq 
		drop eq
		order estimator turnout_pos_req turnout_urne turnout_tot_req	
		texsave using "$tables/Table_E5_ES_tau1_tau0", ///
						align(lccc) hlines(1 -1) autonumber frag replace noendash					
	}				
					